<template>
  <div class="consult">
    <el-row>
      <el-col :span="4">
        <el-card class="box-card" :style="{ height: heightCard }">
          <div slot="header" class="clearfix">
            <span
              style="display: inline-block; font-size: 20px; font-weight: bold"
              >标签分组</span
            >
          </div>
          <div class="tagGroup">
            <ul
              v-for="(group, index) in tagGroups"
              :key="index"
              @click="handleGroupClick(group, index)"
            >
              <li :class="{ active: index === selectedGroupIndex }">
                {{ group.tagName }}
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="box-card" :style="{ height: heightCard }">
          <div slot="header" class="clearfix">
            <span
              style="display: inline-block; font-size: 20px; font-weight: bold"
              >标签分类</span
            >
          </div>
          <div class="tagGroup">
            <ul
              v-for="(category, categoryIndex) in categories"
              :key="categoryIndex"
              @click="handleCategoryClick(categories, categoryIndex)"
            >
              <li :class="{ active: categoryIndex === selectedCategoryIndex }">
                {{ category.tagName }}
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="box-card" :style="{ height: heightCard }">
          <div slot="header" class="clearfix">
            <span
              style="display: inline-block; font-size: 20px; font-weight: bold"
              >标签定义</span
            >
          </div>
          <div class="tagGroup">
            <ul
              v-for="(tags, tagsIndex) in tags"
              :key="tagsIndex"
              @click="handleTagClick(tags, tagsIndex)"
            >
              <li :class="{ active: tagsIndex === selectTagsIndex }">
                {{ tags.tagName }}
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" :style="{ height: heightCard }">
          <div style="display: flex; justify-content: end; padding: 10px"></div>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin: 20px;
            "
          >
            <div style="display: flex;align-items: center;">
              <h4>人员表:</h4>
              <el-input
                size="medium"
                placeholder="请输入姓名"
                v-model="personName"
                clearable
                style="width: 200px;margin-left:10px;"
              />
              <el-input
                size="medium"
                placeholder="请输入身份证号"
                v-model="idCard"
                clearable
                style="width: 200px;margin-left:10px;"
              />
              <el-button size="medium" style="margin-left:10px;" type="primary" @click="getResourceList">查询</el-button>
            </div>
            <el-button size="medium" type="danger" plain @click="handleClickTableDel()">
              删除
            </el-button>
          </div>
          <div style="padding: 0 20px 0 20px">
            <vxe-table
              border
              ref="xTable"
              :resizable="true"
              :align="allAlign"
              :data="tableData"
              :height="heightTable"
              :scroll-y="{ enabled: false }"
              highlight-current-row
              @checkbox-all="handleAllSelectChang"
              @checkbox-change="handleSelectChange"
            >
              <!-- show-overflow -->
              <vxe-column type="checkbox" width="60"></vxe-column>
              <vxe-column
                type="html"
                title="姓名"
                field="NAME"
                :formatter="formatName"
                width="150"
              ></vxe-column>
              <vxe-column
                title="身份证号"
                width="220"
                field="idCard"
              ></vxe-column>
              <vxe-column align="left" title="工作单位及职务" field="jobShort"></vxe-column>
            </vxe-table>
            <vxe-pager
              style="margin-top:10px;"
              background
              align="rigth"
              :current-page.sync="currentPage"
              :page-size.sync="perPage"
              :total="totalItems"
              :layouts="[
                'PrevJump',
                'PrevPage',
                'JumpNumber',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total',
              ]"
              @page-change="handleSizeChange"
            >
            </vxe-pager>
          </div>
        </el-card>
        <personRmb ref="dialogPersonRmb" @onClosed="onClosed"></personRmb>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script>
import store from "@/store";
import Sortable from "sortablejs";
import personRmb from "./componentsConsult/personRmbNewTag";
import {
  consultList,
  tagRequirementDelete,
  tagResourceList,
  tagResourceDelete,
} from "@/api/students/organization/consult";
export default {
  components: { personRmb },
  data() {
    return {
      heightCard: window.innerHeight - 125 + "px",
      heightTable: window.innerHeight - 320 + "px",
      tagGroups: [],
      categories: [],
      tags: [],
      categories: null,
      groupData: null,
      tagsRow: null,
      allAlign: "center",
      tableData: [],
      selectedGroupIndex: 0,
      selectedCategoryIndex: 0,
      selectTagsIndex: 0,
      tagsClickList: null,
      multipleSelection: [],
      selectedRows: [],
      currentPage: 1,
      totalItems: 0,
      perPage: 20,
      idCard: "",
      personName: "",
    };
  },
  computed: {
    currentGroup() {
      return this.tagGroups[this.selectedGroupIndex];
    },
    currentCategory() {
      return this.currentGroup.categories[this.selectedCategoryIndex]; // 默认显示第一个分类
    },
  },
  created() {
    this.rowDrop();
    this.getConsultList();
    let _this = this;
    window.checkPerson = _this.checkPerson;
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
    }
  },
  methods: {
    // 默认展示类似树的数据
    getConsultList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: "-1",
        tagType: "1",
      };
      consultList(params).then((result) => {
        this.tagGroups = result.resultdata.data;
        if (this.tagGroups.length > 0) {
          this.handleGroupClick(this.tagGroups[0], 0); // 获取第一条标签分组数据
        }
      });
    },
    // 点击标签分组
    handleGroupClick(groupData, index) {
      this.groupData = groupData;
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.groupData.id,
        tagType: "2",
      };
      consultList(params).then((result) => {
        this.categories = result.resultdata.data;
        if (this.categories.length > 0) {
          this.handleCategoryClick(this.categories, 0); // 获取第一个标签分类数据并展示第一个标签定义数据
        } else {
          // 清空标签分类和标签定义数据
          this.categories = [];
          this.tags = [];
        }
      });
      this.selectedGroupIndex = index;
      this.selectedCategoryIndex = 0; // 将标签分类下标设置为0
      this.selectTagsIndex = 0; // 将标签定义下标设置为0
    },
    // 点击标签分类
    handleCategoryClick(categories, categoryIndex) {
      this.categories = categories;
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.categories[categoryIndex].id,
        tagType: "3",
      };
      consultList(params).then((result) => {
        this.tags = result.resultdata.data;
        if (this.tags.length > 0) {
          this.handleTagClick(this.tags[0], 0); // 展示第一条标签定义数据
        }
      });
      this.selectedCategoryIndex = categoryIndex;
    },
    // 点击标签定义
    handleTagClick(tags, tagsIndex) {
      this.tagsClickList = tags;
      this.selectTagsIndex = tagsIndex;
      this.getResourceList();
    },
    //查询
    // 获取表格数据
    getResourceList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        tagDefineId: this.tagsClickList.id,
        rows: this.perPage,
        page: this.currentPage,
        idCard:this.idCard,
        name:this.personName,
      };
      tagResourceList(params).then((result) => {
        this.tableData = result.resultdata.data; //表格
        this.totalItems = result.resultdata.count;
      });
    },
    // 分页
    handleSizeChange({ currentPage, pageSize }) {
      console.log(currentPage, pageSize, "212eee");
      this.currentPage = currentPage;
      this.perPage = pageSize;
      this.getResourceList();
    },
    formatName({ row, rowIndex }) {
      return (
        '<a href="javascript:void(0)" style="color:#0220bf;cursor:pointer" onclick="checkPerson(\'' +
        row.personId +
        "','" +
        rowIndex +
        "','" +
        0 +
        "')\">" +
        row.NAME +
        "</a>"
      );
    },
    // 点击人员查看详情
    checkPerson(personId, index, personEdit) {
      // this.crentRowIndex = index;
      this.$refs.xTable.setCurrentRow(this.tableData[index]);
      if (personId && personId != "null") {
        this.$refs.dialogPersonRmb.initData(
          personId,
          personEdit,
          "人员修改",
          "personNew"
        );
      } else {
        this.$message.warning("打开失败（主键标识未获取到），请联系管理员！");
      }
    },
    onClosed() {
      // this.getResourceList()
    },
    handleSelectChange({ checked }) {
      this.selectedRows = [];
      this.multipleSelection = [];
      const records = this.$refs.xTable.getCheckboxRecords();
      this.selectedRows = records; // 将选中的行数据赋值给 selectedRows 数组
      console.log(this.selectedRows, "单选");
    },
    handleAllSelectChang({ checked, records }) {
      this.selectedRows = [];
      this.multipleSelection = [];
      this.multipleSelection = records;
      console.log(this.multipleSelection, "多选");
    },
    // 表格删除
    handleClickTableDel() {
      let dataList = this.selectedRows.length || this.multipleSelection.length;
      if (dataList !== 0) {
        this.$confirm("确定删除当前行?", "操作提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const params = {
            userId: store.getters.user_id.toString(),
            userName: store.getters.userName.toString(),
            token: store.getters.token.toString(),
            list: [],
          };
          if (this.selectedRows.length > 0) {
            // 如果有选中的行，则将选中的行数据放入 list 中
            params.list = this.selectedRows.map((row) => ({ ...row }));
          } else if (this.multipleSelection.length > 0) {
            // 如果没有选中的行，但有多选的行，则将多选的行数据放入 list 中
            params.list = this.multipleSelection.map((row) => ({ ...row }));
          }

          tagResourceDelete(params).then((response) => {
            if (response.result) {
              this.$message({
                type: "success",
                message: response.resultdata,
              });
              this.getConsultList();
            } else {
              this.$message({
                type: "error",
                message: response.resultdata,
              });
            }
          });
        });
      } else {
        // 如果既没有选中的行，也没有多选的行，则提示用户至少选择一行
        this.$message({
          type: "warning",
          message: "请至少勾选一条数据要删除的数据！",
        });
      }
    },
    rowDrop() {
      this.$nextTick(() => {
        let xTable = this.$refs.xTable;
        this.sortable = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".vxe-body--row",
            animation: 150,
            onEnd: ({ newIndex, oldIndex }) => {
              // 拖拽后回调
              /*
	            常规想法
				此方法数组处理正常，但表格渲染顺序有问题
	            */
              // let currRow = this.tableData.splice(oldIndex, 1)[0];
              // this.tableData.splice(newIndex, 0, currRow);

              // 解决方案
              this.tableData.splice(
                newIndex,
                0,
                this.tableData.splice(oldIndex, 1)[0]
              );
              var newArray = this.tableData.slice(0);
              this.tableData = [];
              this.$nextTick(function () {
                this.tableData = newArray;
              });
            },
          }
        );
      });
    },

    // 添加成功或者编辑成功，回调方法
    handleGroupAddSuccess(e) {
      const { type, data } = e;
      // 这个 type 你到时候可以用来干嘛用，现在我不做任何作用，只是给你暴露出来，可能你会用到
      const list = this.tagGroups;
      if (Array.isArray(list)) {
        let index = list.findIndex((f) => f === data);
        this.handleGroupClick(data, index < 0 ? 0 : index);
      }
    },
  },
};
</script>
<style scoped>
.consult {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
}

.tagGroup ul {
  list-style: none;
}

.tagGroup ul li {
  padding: 20px;
  border-bottom: 1px solid #eee;
}
.active {
  /* background: #ecf5ff;
  color: #409eff; */
  background: #cfe5fc;
  color: #000;
}
>>> .el-card__header {
  background: linear-gradient(180deg, #fff, #ededed);
}
>>> .el-card__body {
  padding: 0;
}
</style>